JDBC Transaction

Categories: Java; Tagged with: ; @ February 19th, 2009 10:12

默认下JDBC是Auto-commit的. 但在必要情况下, 我们需要手动控制事务, 此时:

con.setAutoCommit(false); //关闭自动Commit
PreparedStatement updateSales = con.prepareStatement(
    "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();//执行Update Sales操作
PreparedStatement updateTotal = con.prepareStatement(
    "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();//执行Update Total操作, 注意, 此二者必须同时执行成功 或同时失败.
con.commit(); //commit以上两个操作, 同时成功或失败
con.setAutoCommit(true); //将AutoCommit恢复为true

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.